// @flow
import { createAction, handleActions, type ActionType } from 'redux-actions';
import { delay } from 'redux-saga';
import produce from 'immer';

/* ACTION TYPES */
const PLAIN = 'sample/PLAIN';
const INCREASE = 'sample/INCREASE';
const INSERT = 'sample/INSERT';
const CHANGE = 'sample/CHANGE';

/* ACTION PAYLOADS */
type InsertPayload = {
  id: number,
  text: string,
};
/* EXPORTING ACTION CREATORS / ACTION CREATORS TYPES */
export interface SampleActionCreators {
  plain(): any;
  increase(value: number): any;
  insert(payload: InsertPayload): any;
  change(text: string): any;
}

/* ACTION CREATORS */
export const actionCreators: SampleActionCreators = {
  plain: createAction(PLAIN),
  increase: createAction(INCREASE, (value: number) => value),
  insert: createAction(INSERT, ({ id, text }: InsertPayload): InsertPayload => ({ id, text })),
  change: createAction(CHANGE, (text: string) => text),
};

/* ACTION FLOW TYPES */
type PlainAction = ActionType<typeof actionCreators.plain>;
type IncreaseAction = ActionType<typeof actionCreators.increase>;
type InsertAction = ActionType<typeof actionCreators.insert>;
type ChangeAction = ActionType<typeof actionCreators.change>;
/* State Types */
type TodoItem = {
  id: number,
  text: string,
  done: boolean,
};

export type Sample = {
  value: number,
  text: string,
  todos: TodoItem[],
};

const initialState: Sample = {
  value: 0,
  text: '',
  todos: [],
};

const reducers = handleActions(
  {
    [PLAIN]: (state, action: PlainAction) => state,
    [INCREASE]: (state, action: IncreaseAction) => {
      return produce(state, (draft) => {
        if (!action || !draft) return;
        draft.value = action.payload;
      });
    },
    [INSERT]: (state, action: InsertAction) => {
      return produce(state, (draft) => {
        if (!action || !draft) return;
        draft.todos.push({ ...action.payload, done: false });
      });
    },
    [CHANGE]: (state, action: ChangeAction) => {
      return produce(state, (draft) => {
        if (!action || !draft) return;
        draft.text = action.payload;
      });
    },
  },
  initialState,
);
const effects = function* rootSaga() {
  yield console.log('hello');
};
export default { reducers, effects };
